package com.java.controller;

import com.java.bean.Car;
import com.java.service.Impl.CarServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@Repository
public class CarController {
    @Autowired
    private CarServiceImpl carService;

    @RequestMapping(value = "/login")
    public String login(Model model) {
        return "login";
    }


    @RequestMapping(value = "/listAll")
    public String listAll(Model model) {
        List<Car> car = carService.selectAll();
        model.addAttribute("car", car);
        return "listAll";
    }

    @RequestMapping(value = "/select")
    public String select(Model model) {
        List<Car> car = carService.selectAll();
        model.addAttribute("car", car);
        return "select";
    }

    //修改页面
    @RequestMapping(value = "/toUpdate")
    public String update(int id, Model model) {
        Car car = carService.selectCarByid(id);
        model.addAttribute("car", car);
        return "update";
    }

    //修改汽车功能
    @ResponseBody
    @RequestMapping(value = "/updateCar", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    public String update(Car car) {
        int i = carService.updateCar(car);
        if (i > 0) {
            return "<script>alert('汽车修改成功');location.href='/listAll'</script>";
        } else {
            return "<script>alert('汽车修改失败');history.go=(-1)</script>";
        }
    }

    @RequestMapping(value = "/addCars")
    public String addCar() {
        return "addCar";
    }

    //添加汽车功能
    @ResponseBody
    @RequestMapping(value = "/addCar", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    public String addCar(Car car) {
        int i = carService.addCar(car);
        if (i > 0) {
            return "<script>alert('汽车添加成功');location.href='/listAll'</script>";
        } else {
            return "<script>alert('汽车添加失败');history.go=(-1)</script>";
        }
    }

    //删除汽车
    @ResponseBody
    @RequestMapping(value = "/delete/{id}", produces = "text/html;charset=UTF-8")
    public String delete(@PathVariable("id") Integer id) {
        int i = carService.deleteCar(id);
        if (i > 0) {
            return "<script>alert('汽车删除成功');location.href='/listAll'</script>";
        } else {
            return "<script>alert('汽车删除失败');history.go=(-1)</script>";
        }
    }
}
